#pragma once
#include <iostream>
#include <string>
#include <map>
// Http request

namespace protocol_ns
{
    class Request
    {
    public:
        enum Method
        {
            GET,
            POST,
            Invalid
        };

        enum Version
        {
            Unknown,
            Http10,
            Http11
        };

        Method toMethod(std::string method)
        {

            if (method == "POST")
                return POST;
            else if (method == "GET")
                return GET;
            else
            {
                return Invalid;
            }
        }

        Version toVersion(std::string version)
        {
            if (version.find("1.1"))
                return Http11;
            else if (version.find("1.0"))
                return Http10;
            else
                return Unknown;
        }

        void removeSpace(std::string &str)
        {
            int i = 0;
            while (str[i] == ' ')
            {
                i++;
            }

            str = str.substr(i);
        }

        Request() : method_(Invalid), version_(Unknown)
        {
        }

        ~Request() {}

        bool Serialize(std::string *outStr)
        {
        }

        // string->struct
        bool Deserialize(const std::string &inStr)
        {
            // 1 先找到第一个换行
            int pos1 = inStr.find_first_of("\n");
            std::string s_head = inStr.substr(0, pos1);

            // 1.1 处理三个内容
            int pos_pre = s_head.find_first_of(' ');
            int pos_end = s_head.find_last_of(' ');

            method_ = toMethod(s_head.substr(0, pos_pre));
            path_ = s_head.substr(pos_pre + 1, pos_end - pos_pre - 1);
            version_ = toVersion(s_head.substr(pos_end + 1));

            // 2 找\r\n
            int pos2 = inStr.find_last_of("\n");
            std::string s_lines = inStr.substr(pos1 + 1, pos2 - pos1 - 1);

            // std::cout << s_lines << std::endl;

            // 2.1添加里面所有的line
            int start = 0;
            int pos = s_lines.find("\n", 0);
            while (pos != std::string::npos)
            {
                // 找到一条数据
                std::string tmp = s_lines.substr(start, pos - start);
                // 解析
                int tmpi = tmp.find(":");
                std::string key = tmp.substr(0, tmpi);

                std::string val = tmp.substr(tmpi + 1);
                removeSpace(val);

                // 添加
                headers_[key] = val;

                // 继续找
                start = pos + 1;
                pos = s_lines.find("\n", start);
            }

            // 3 找请求体
            std::string body = inStr.substr(pos2 + 1);
        }

    private:
        Version version_;
        std::string path_;
        std::string query_;
        Method method_;
        std::map<std::string, std::string> headers_;
    };
}
